package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.log.LogMbdDxf;
import com.zmj.sy.mom.srv.aps.bean.entity.log.LogNestExce;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.*;
import com.zmj.sy.mom.srv.aps.bean.entity.order.*;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.LogApi;
import com.zmj.sy.mom.srv.aps.bean.entity.third.*;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.newNest.ReceiveNestExcessReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.newNest.ReceiveNestMoveReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.newNest.ReceiveNestPartReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.newNest.ReceiveNestPlateReqVo;
import com.zmj.sy.mom.srv.aps.config.ProjectConfig;
import com.zmj.sy.mom.srv.aps.feign.ApsMesFeign;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.utils.*;
import com.zmj.sy.mom.srv.mbd.api.api.MomSrvMbdApiClient;
import com.zmj.sy.mom.srv.mbd.api.bean.dto.BaseListResDto;
import com.zmj.sy.mom.srv.mbd.api.bean.dto.BaseResDto;
import com.zmj.sy.mom.srv.mbd.api.bean.dto.mesdxf.MesDxfConfirmDataReqDto;
import com.zmj.sy.mom.srv.mbd.api.bean.dto.mesdxf.MesDxfFindResDto;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RequiredArgsConstructor
@Service
public class DxfService {

    private static final Logger log = LoggerFactory.getLogger(DxfService.class);
    private final MomSrvMbdApiClient momSrvMbdApiClient;

    private final ImportMbdDxfMapper importMbdDxfMapper;
    private final OrderMapper orderMapper;
    private final ApsWorkDetailMapper apsWorkDetailMapper;
    private final OrderBomMapper orderBomMapper;
    private final SinoCamPushDrawingMapper sinoCamPushDrawingMapper;
    private final OrderPartMapper orderPartMapper;
    private final SinoCamService sinoCamService;
    private final LogMbdDxfMapper logMbdDxfMapper;
    private final BaseConfigMapper baseConfigMapper;
    private final LogMessageMapper logMessageMapper;
    private final SinoCamReceiveNestPartMapper sinoCamReceiveNestPartMapper;
    private final MkHttpUtils mkHttpUtils;
    private final ProjectConfig projectConfig;
    private final SinoCamReceiveNestCheckMapper sinoCamReceiveNestCheckMapper;
    private final PlateMapper plateMapper;
    private final PlateService plateService;
    private final MesNestPartMapper mesNestPartMapper;
    private final ApsMesFeign apsMesFeign;
    private final WmsPlatePickMapper wmsPlatePickMapper;
    private final SinoCamMapper sinoCamMapper;
    private final SinoCamPushPlanMapper sinoCamPushPlanMapper;
    private final SinoCamReceiveNestMapper sinoCamReceiveNestMapper;
    private final SinoCamReceiveNestExcessMapper sinoCamReceiveNestExcessMapper;
    private final SinoCamReceiveNestNestMapper sinoCamReceiveNestNestMapper;
    private final SinoCamReceiveNestPlateMapper sinoCamReceiveNestPlateMapper;
    private final SinoCamReceiveNestMoveMapper sinoCamReceiveNestMoveMapper;
    private final HexagonPackagePushMapper hexagonPackagePushMapper;
    private final PlatePhaseMapper platePhaseMapper;
    private final PickMapper pickMapper;
    private final HexagonNestOldUtils hexagonNestOldUtils;
    private final LogNestExceMapper logNestExceMapper;
    private final WorkRecordMapper workRecordMapper;
    private final PartMapper partMapper;

    @Value("${project.feign.dxf-download}")
    private String dxfDownload;

    @Value("${project.feign.mes-url-png}")
    private String mesPNG;

    @Value("${project.feign.mes-url-dxf}")
    private String mesDXF;

    private BiConsumer<LogApi, String> consumer = (LogApi logApi, String body) -> {
        JsonNode jsonNode = JsonUtils.readTree(body);
        if (jsonNode.get("success").asBoolean()) { // 判断 body 中的 Success，为 true 还是 false
            logApi.setSuccess(true);
        } else {
            logApi.setSuccess(false);
            logApi.setErrorMsg(jsonNode.get("message").asText());
        }
    };

    @Transactional
    public List<Integer> exec() {
        // 1.获取mbd未读的记录
        BaseListResDto<MesDxfFindResDto> sourceList = momSrvMbdApiClient.mesDxfFind();

        if (CollUtil.isEmpty(sourceList.getData())) {
            return new ArrayList<>();
        }

        // 2.入库
        List<ImportMbdDxf> batchList = sourceList.getData()
                .stream()
                .map(e -> {
                    ImportMbdDxf dxf = new ImportMbdDxf();
                    String plmId = e.getPlmid().endsWith("_170") ? e.getPlmid().substring(0, e.getPlmid().length() - 4) : e.getPlmid();
                    dxf.setPlmid(plmId);
                    dxf.setPath(e.getPath());
                    dxf.setFileName(e.getFileName());
                    dxf.setDocNumber(e.getDocNumber());
                    dxf.setDocName(e.getDocName());
                    dxf.setDocVersion(e.getDocVersion());
                    dxf.setCreateTime(DateUtil.toLocalDateTime(e.getCreateTime()));
                    dxf.setCreateNum(e.getCreateNum());
                    dxf.setCreateName(e.getCreateName());
                    dxf.setModifyNum(e.getCreateNum());
                    dxf.setModifyName(e.getCreateName());
                    return dxf;
                })
                .collect(Collectors.toList());

        List<LogMbdDxf> logMbdDxfList = batchList.stream().map(e -> MkBeanUtils.copyProperties(e, LogMbdDxf.class)).collect(Collectors.toList());
        logMbdDxfMapper.insertBatch(logMbdDxfList, 500);

        // 3.更新数据库中的记录，只保留最后一条
        List<String> plmIdList = batchList.stream().map(ImportMbdDxf::getPlmid).collect(Collectors.toList());
        List<ImportMbdDxf> list = importMbdDxfMapper.lambdaQuery().in(ImportMbdDxf::getPlmid, plmIdList).list();
        batchList.addAll(list);
        Map<String, ImportMbdDxf> dxfPlmIdMap = batchList.stream()
                .collect(Collectors.toMap(e -> e.getPlmid().endsWith("_170") ? e.getPlmid().substring(0, e.getPlmid().length() - 4) : e.getPlmid(), e -> e, (e1, e2) -> {

                    if (e1.getCreateTime().isAfter(e2.getCreateTime())) {
                        e1.setCreateName(e2.getCreateName());
                        e1.setCreateNum(e2.getCreateNum());
                        if (e2.getId() != null) {
                            e1.setId(e2.getId());
                            e1.setCreateDateTime(e2.getCreateDateTime());
                            e1.setModifyDateTime(e2.getModifyDateTime());
                            e1.setCreateUsername(e2.getCreateUsername());
                            e1.setModifyUsername(e2.getModifyUsername());
                        }
                        return e1;
                    }

                    e2.setCreateName(e1.getCreateName());
                    e2.setCreateNum(e1.getCreateNum());
                    if (e1.getId() != null) {
                        e2.setId(e2.getId());
                        e2.setCreateDateTime(e2.getCreateDateTime());
                        e2.setModifyDateTime(e2.getModifyDateTime());
                        e2.setCreateUsername(e2.getCreateUsername());
                        e2.setModifyUsername(e2.getModifyUsername());
                    }

                    return e2;
                }));

        // applyDrawUpdate(list.stream().map(ImportMbdDxf::getPlmid).collect(Collectors.toList()));

//        Map<String, ImportMbdDxf> dxfPlmIdMap1 = new HashMap<>();
//        for (Map.Entry<String, ImportMbdDxf> stringImportMbdDxfEntry : dxfPlmIdMap.entrySet()) {
//            dxfPlmIdMap1.put(stringImportMbdDxfEntry.getKey(), stringImportMbdDxfEntry.getValue());
//        }
//        dxfPlmIdMap = dxfPlmIdMap1;
//        for (ImportMbdDxf value : dxfPlmIdMap.values()) {
//            String key = value.getPlmid().endsWith("_170") ? value.getPlmid() : value.getPlmid().substring(0, value.getPlmid().length() - 4); // 后续修改 "_170"
//            ImportMbdDxf newDxf = new ImportMbdDxf();
//            BeanUtils.copyProperties(value, newDxf);
//            dxfPlmIdMap1.put(key, newDxf);
//        }

//        dxfPlmIdMap.putAll(dxfPlmIdMap1);
//        Collection<ImportMbdDxf> values = dxfPlmIdMap.values();
        Map<String, ImportMbdDxf> hasMap = list.stream().collect(Collectors.toMap(ImportMbdDxf::getPlmid, Function.identity()));
        List<ImportMbdDxf> addList = dxfPlmIdMap.values()
                .stream()
                .filter(e -> hasMap.get(e.getPlmid()) == null)
                .collect(Collectors.toList());
        importMbdDxfMapper.insertBatch(addList);

        List<ImportMbdDxf> updateList = dxfPlmIdMap.values()
                .stream()
                .filter(e -> hasMap.get(e.getPlmid()) != null)
                .collect(Collectors.toList());
        for (ImportMbdDxf importMbdDxf : updateList) {
            importMbdDxfMapper.updateById(importMbdDxf);
        }

        // 4.MBD已读
        List<MesDxfConfirmDataReqDto> confirmData = sourceList.getData()
                .stream()
                .map(e -> {
                    MesDxfConfirmDataReqDto reqDto = new MesDxfConfirmDataReqDto();
                    reqDto.setPlmid(e.getPlmid());
                    reqDto.setCreateTime(e.getCreateTime());
                    return reqDto;
                })
                .collect(Collectors.toList());
        BaseResDto baseResDto = momSrvMbdApiClient.mesDxfConfirm(confirmData);
        if (baseResDto.getCode() != 0) {
            throw SyExceptionUtils.e(baseResDto.getMessage());
        }


        List<OrderPart> orderPartList = orderPartMapper.lambdaQuery().in(OrderPart::getPlmId, dxfPlmIdMap.keySet().stream().flatMap(e -> Stream.of(e, e + "_170")).collect(Collectors.toList())).list();

        for (OrderPart orderPart : orderPartList) {
            String plmId = orderPart.getPlmId().endsWith("_170") ? orderPart.getPlmId().substring(0, orderPart.getPlmId().length() - 4) : orderPart.getPlmId();
            ImportMbdDxf importMbdDxf = dxfPlmIdMap.get(plmId);
            orderPart.setDxfUrl(importMbdDxf.getPath());
            orderPart.setDrawUpdateTime(importMbdDxf.getCreateTime());
            orderPart.setVersionNum(importMbdDxf.getDocVersion());
            orderPart.setDrawStatus(2);
            orderPart.setVersionCode(orderPart.getVersionCode() + 1);
            orderPartMapper.updateById(orderPart);
        }

        // 查看已套料的、进行中的订单
        List<Order> orderList = orderMapper.lambdaQuery().in(Order::getOrderStatus, 7, 8).list();
        if (CollUtil.isEmpty(orderList)) {
            return new ArrayList<>();
        }

        List<Integer> orderIdList = orderList.stream().map(BaseEntity::getId).distinct().collect(Collectors.toList());

        // 找到这几个订单中，是否包含此零件
        List<String> allPlmIdList = new ArrayList<>(dxfPlmIdMap.keySet());
        for (String s : dxfPlmIdMap.keySet()) {
            allPlmIdList.add(s + "_170");
        }
        List<OrderBom> cont = orderBomMapper.lambdaQuery()
                .in(OrderBom::getOrderId, orderIdList)
                .in(OrderBom::getPlmId, allPlmIdList)
                .list();

        if (CollUtil.isEmpty(cont)) {
            return new ArrayList<>();
        }

        List<SinoCamPushDrawing> list1 = sinoCamPushDrawingMapper.lambdaQuery()
                .in(SinoCamPushDrawing::getPartId, allPlmIdList)
                .in(SinoCamPushDrawing::getOrderId, orderIdList)
                .list();
        for (SinoCamPushDrawing sinoCamPushDrawing : list1) {
            sinoCamPushDrawing.setStatus(2);
            sinoCamPushDrawing.setDrawStatus(2);
            sinoCamPushDrawing.setVersionNum(sinoCamPushDrawing.getVersionNum() + 1);
            String plmId = sinoCamPushDrawing.getPartId().endsWith("_170") ? sinoCamPushDrawing.getPartId().substring(0, sinoCamPushDrawing.getPartId().length() - 4) : sinoCamPushDrawing.getPartId();
            ImportMbdDxf dxf = dxfPlmIdMap.get(plmId);
            sinoCamPushDrawing.setFilePath(dxfDownload + dxf.getPath());
            sinoCamPushDrawing.setErrorMsg("图纸已补充/更新。");
            sinoCamPushDrawingMapper.updateById(sinoCamPushDrawing);
        }
//        orderMapper.lambdaUpdate().eq(Order::getPushStatus, 3).in(Order::getId, orderIdList).set(Order::getPushStatus, 2).update();

        return list1.stream().map(SinoCamPushDrawing::getOrderId).collect(Collectors.toList());
    }

    public void getPngByPlmId() {
        List<OrderPart> list = orderPartMapper.lambdaQuery()
                .eq(OrderPart::getMaterType, "Platepart")
                .isNull(OrderPart::getPngUrl)
                .ge(OrderPart::getCreateDateTime, LocalDate.now().minusMonths(1))
                .list();
        for (OrderPart a : list) {
            try {
                sinoCamService.getPngPlmId(a.getPlmId());
            } catch (Exception e) {
                log.info("获取零件图失败：{}", a.getPlmId());
            }
        }
    }

    public void fillOrderPart() {
        QueryWrapper<OrderPart> qw = new QueryWrapper<>();
        qw.ge("create_date_time", LocalDate.now().minusMonths(1));
        qw.eq("mater_type", "Platepart");
        qw.and(wp->wp.isNull("length").or().isNull("width").or().isNull("area").or().isNull("nest_weight").or().isNull("png_url"));
        List<OrderPart> orderPartList = orderPartMapper.selectList(qw);
        List<SinoCamReceiveNestPart> nestPartList = sinoCamReceiveNestPartMapper.lambdaQuery().in(SinoCamReceiveNestPart::getPartId, orderPartList.stream().map(OrderPart::getPlmId).collect(Collectors.toList())).list();
        Map<String, List<SinoCamReceiveNestPart>> nestPartMap = nestPartList.stream().collect(Collectors.groupingBy(SinoCamReceiveNestPart::getPartId));
        for (OrderPart p : orderPartList) {
            List<SinoCamReceiveNestPart> nestPart = nestPartMap.get(p.getPlmId());
            if (CollUtil.isNotEmpty(nestPart)) {
                p.setLength(nestPart.get(0).getLength());
                p.setWidth(nestPart.get(0).getWidth());
                p.setArea(nestPart.get(0).getArea());
                p.setPngUrl(nestPart.get(0).getPartMapUrl());
                p.setNestWeight(nestPart.get(0).getNetWeight());
                orderPartMapper.updateById(p);
            }
        }
    }

    public void checkNestZeroInfo() {

        // 获取需要切割的工序
        List<String> phaseCodeList = projectConfig.getCuttingProcess();

        List<SinoCamReceiveNestCheck> list = sinoCamReceiveNestCheckMapper.lambdaQuery()
                .eq(SinoCamReceiveNestCheck::getCheckState, 0)
                .orderByDesc(SinoCamReceiveNestCheck::getId)
                .list();
        if (CollUtil.isEmpty(list)) {
            return;
        }
//        Collection<SinoCamReceiveNestCheck> values = list.stream().collect(Collectors.toMap(e -> e.getNestId(), Function.identity(), (e1, e2) -> e1)).values();
//        List<SinoCamReceiveNestCheck> sinoCamReceiveNestChecks = new ArrayList<>(values);
        List<SinoCamReceiveNestCheck> collect = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SinoCamReceiveNestCheck::getNestId))), ArrayList::new));
        for (SinoCamReceiveNestCheck nestCheck : collect) {
            try {
                List<ReceiveNestPlateReqVo> plateVos = apsMesFeign.receiveNestInfoNestId(nestCheck.getNestId());
                if (CollUtil.isNotEmpty(plateVos)) {
                    for (ReceiveNestPlateReqVo plateVo : plateVos) {
                        WmsPlatePick platePick = wmsPlatePickMapper.lambdaQuery()
                                .eq(WmsPlatePick::getNestId, plateVo.getNestId())
                                .eq(WmsPlatePick::getMaterialCode, plateVo.getPlateCode())
                                .ne(WmsPlatePick::getPlateState, 1)
                                .one();
                        if (!ObjectUtils.isEmpty(platePick)) {
                            continue;
                        }
                        // 钢板处于未领料状态，则清除信息，重新获取
                        sinoCamService.clearNestResultInfoPlate(plateVo.getPlateCode());
                        // 对套料结果的信息进行处理
                        ReceiveNestPlateReqVo reqVo = sinoCamService.handleNestResult(plateVo);
                        // 查询钢板上零件的推送计划
                        List<ReceiveNestPartReqVo> partList = reqVo.getPart();

                        List<SinoCamPushPlan> pushPlanList = sinoCamPushPlanMapper.lambdaQuery()
                                .in(SinoCamPushPlan::getProductId, partList.stream().map(ReceiveNestPartReqVo::getConstructNo).collect(Collectors.toList()))
                                .in(SinoCamPushPlan::getPartId, partList.stream().map(ReceiveNestPartReqVo::getPartId).collect(Collectors.toList()))
                                .orderByAsc(SinoCamPushPlan::getProcessingNo)
                                .list();

                        if (CollUtil.isEmpty(pushPlanList)) {
                            continue;
                        }

                        Optional<SinoCamPushPlan> min = pushPlanList.stream().min(Comparator.comparing(SinoCamPushPlan::getNeedDate));
                        LocalDateTime needDate = min.get().getNeedDate();
                        String needDateTime = needDate.format(DatePattern.NORM_DATETIME_FORMATTER);

                        SinoCam sc = new SinoCam();
                        sc.setName("5-接收计划");
                        sc.setType(5);
                        sc.setStatus(1);
                        sc.setResult(3);
                        sc.setUniNum(sc.getOrderId() + "-" + sc.getType());

                        sinoCamMapper.insert(sc);

                        SinoCamReceiveNest scrn = new SinoCamReceiveNest();
                        scrn.setSinoCamId(sc.getId());
                        sinoCamReceiveNestMapper.insert(scrn);

                        List<SinoCamReceiveNestPlate> plateAll = new ArrayList<>();
                        List<SinoCamReceiveNestNest> nestAll = new ArrayList<>();

                        int scId = sc.getId();
                        int scrnId = scrn.getId();
                        // 套料
                        SinoCamReceiveNestNest nn = sinoCamReceiveNestNestMapper.lambdaQuery().eq(SinoCamReceiveNestNest::getNestId, reqVo.getNestId()).one();
                        if (nn == null) {
                            SinoCamReceiveNestNest nestEntity = MkBeanUtils.copyProperties(reqVo, SinoCamReceiveNestNest.class);
                            nestEntity.setSinoCamId(sc.getId());
                            nestEntity.setReceiveNestId(scrn.getId());
                            nestEntity.setNestId(reqVo.getNestId());
                            nestEntity.setFactoryIdk("170");
                            nestEntity.setCutNozzleNorm(reqVo.getCutNozzleNorm());
                            nestEntity.setCutNozzleNumber(reqVo.getCutNozzleNumber());
                            nestEntity.setCutNozzleDistance(reqVo.getCutNozzleDistance());
                            nestEntity.setWidth(reqVo.getWidth());
                            nestEntity.setLength(reqVo.getLength());
                            nestEntity.setNestDate(reqVo.getNestDateTime());
                            nestEntity.setChangeDate(reqVo.getChangeDateTime());
                            nestEntity.setNeedDate(needDateTime);
                            nestEntity.setNester(reqVo.getNester());
                            nestEntity.setChanger(reqVo.getChanger());
                            nestEntity.setOptionId(reqVo.getGroupCode());
                            nestEntity.setSplitGroupCode(reqVo.getGroupCode());
                            nestEntity.setNestDxfUrl(mesDXF + reqVo.getDxfUrl());
                            LocalDateTime nowDateTime = LocalDateTime.now();
                            String nowTime = nowDateTime.format(DatePattern.PURE_DATE_FORMATTER);
                            nestEntity.setBookSheet(nowTime);
                            nestEntity.setReportPdfUrl(reqVo.getReportPdfUrl());
                            nestEntity.setCuttingProgramUrl(reqVo.getCuttingProgramUrl());
                            nestEntity.setRate(reqVo.getRate()); // 利用率，钢板减去余料，再与零件重量进行计算，得到利用率
                            nestEntity.setVersionBrief("V2");
                            sinoCamReceiveNestNestMapper.insert(nestEntity);
                            nestAll.add(nestEntity);

                            log.info("套料:{}", JsonUtils.toJsonString(nestEntity));
                        } else {
                            scId = nn.getSinoCamId();
                            scrnId = nn.getReceiveNestId();
                        }

                        // 零件
                        List<ReceiveNestPartReqVo> receiveNestParts = reqVo.getPart();
                        List<SinoCamReceiveNestPart> receiveParts = new ArrayList<>();

                        for (ReceiveNestPartReqVo e : receiveNestParts) {

                            if (!StringUtils.hasText(e.getMesOrderCode())) {
                                continue;
                            }

                            if (!StringUtils.hasText(e.getMesPkgCode())) {
                                continue;
                            }

                            HexagonPackagePush hexagonPush = hexagonPackagePushMapper.lambdaQuery()
                                    .eq(HexagonPackagePush::getMesOrderCode, e.getMesOrderCode())
                                    .eq(HexagonPackagePush::getPackageCode, e.getMesPkgCode())
                                    .one();

                            if (hexagonPush == null) {
                                continue;
                            }

                            List<SinoCamPushPlan> pushOneList = sinoCamPushPlanMapper.lambdaQuery()
                                    .eq(SinoCamPushPlan::getApsOrderId, hexagonPush.getApsOrderId())
                                    .eq(SinoCamPushPlan::getPath, e.getPath())
                                    .eq(SinoCamPushPlan::getPartId, e.getPartId())
                                    .list();
                            if (CollUtil.isEmpty(pushOneList)) {
                            } else {
                                if (pushOneList.size() > 1) {
                                } else {
                                    SinoCamPushPlan pushOne = pushOneList.get(0);

                                    SinoCamReceiveNestPart part = MkBeanUtils.copyProperties(e, SinoCamReceiveNestPart.class);
                                    part.setSinoCamId(scId);
                                    part.setReceiveNestId(scrnId);
                                    part.setNestId(reqVo.getNestId());
                                    part.setNestPlanId(pushOne.getNestPlanId());
                                    part.setPartId(pushOne.getPartId());
                                    part.setPartName(e.getPartName());
                                    part.setQuantity(e.getQuantity());
                                    part.setNetWeight(e.getNetWeight());
                                    part.setArea(e.getArea() != null ? e.getArea() : BigDecimal.ZERO);
                                    part.setRectangleArea(e.getRectangleArea() != null ? e.getRectangleArea() : BigDecimal.ZERO);
                                    part.setRequireFactoryId(e.getFactoryCode());
                                    part.setWidth(e.getWidth());
                                    part.setLength(e.getLength());
                                    if (e.getThickness() == null) {
                                        part.setThickness(reqVo.getThickness());
                                    } else {
                                        part.setThickness(e.getThickness());
                                    }
                                    part.setPartMapUrl(mesPNG + e.getPngUrl());
                                    part.setPlateCode(e.getPlateCode());
                                    part.setSortingCount(0);// 分拣数量
                                    part.setUniCode(pushOne.getUniMaterCode());
                                    part.setSortState(0);

                                    part.setOrderId(pushOne.getOrderId());
                                    part.setWorkOrderCode(e.getWorkOrderCode());
                                    part.setMesOrderCode(e.getMesOrderCode());
                                    part.setMesPkgCode(e.getMesPkgCode());
                                    part.setMesLineId(e.getLineId());

                                    pushOne.setPlanFinishAmount(pushOne.getPlanFinishAmount().add(BigDecimal.valueOf(e.getQuantity())));
                                    receiveParts.add(part);
                                    pushOne.setStatus(4);
                                    pushOne.setErrorMsg("已回填数据。");
                                    sinoCamPushPlanMapper.updateById(pushOne);

                                    /*if (pushOne.getPlanFinishAmount().compareTo(pushOne.getPlanAmount()) > 0) {
                                        BaseIdReqVo vo = new BaseIdReqVo();
                                        vo.setId(Integer.parseInt(pushOne.getNestPlanId()));
                                        sinoCamService.checkNestExist(vo);
                                    }*/

                                }
                            }

                        }

                        if(CollUtil.isNotEmpty(receiveParts)){
                            sinoCamReceiveNestPartMapper.insertBatchSomeColumn(receiveParts);
                        }

                        log.info("零件:{}", JsonUtils.toJsonString(receiveParts));

                        // 钢板
                        SinoCamReceiveNestPlate plate = MkBeanUtils.copyProperties(reqVo, SinoCamReceiveNestPlate.class);
                        BigDecimal bigDecimal = new BigDecimal(1);
                        BigDecimal amount = bigDecimal.setScale(0, RoundingMode.HALF_UP);
                        plate.setAmount(amount);
                        plate.setHeatNumber(reqVo.getHeatId());
                        plate.setSinoCamId(scId);
                        plate.setReceiveNestId(scrnId);
                        plate.setNestId(reqVo.getNestId());
                        plate.setStockListNo(reqVo.getPlateCode());
                        plate.setMaterielName(reqVo.getPlateCode());
                        plate.setFactoryIdk("170");
                        plate.setTexture(reqVo.getTexture());
                        plate.setNorm(reqVo.getThickness().setScale(0, RoundingMode.HALF_UP).toString());
                        plate.setWidth(reqVo.getWidth());
                        plate.setLength(reqVo.getLength());
                        plate.setStorehouseId(reqVo.getStoreCode());
                        plate.setSequence(reqVo.getSequence());
                        plate.setLayer(reqVo.getSequence());
                        plate.setIsVirtual(false);
                        plate.setRate(reqVo.getRate());
                        plate.setSideLength(reqVo.getSideLength());
                        plate.setStatus(1);// 领料状态
                        plate.setPngUrl(mesPNG + reqVo.getPngUrl());
                        plate.setPositionCode(reqVo.getPositionCode());
                        plate.setNestArea(reqVo.getNxusedarea());

                        sinoCamReceiveNestPlateMapper.insert(plate);
                        plateAll.add(plate);

                        log.info("钢板:{}", JsonUtils.toJsonString(plate));

                        // 余料
                        List<ReceiveNestExcessReqVo> excessListVo = reqVo.getExcess();
                        if (CollUtil.isNotEmpty(excessListVo)) {
                            ReceiveNestExcessReqVo excessVo = excessListVo.get(0);
                            List<SinoCamReceiveNestExcess> excessList = sinoCamReceiveNestExcessMapper.lambdaQuery()
                                    .eq(SinoCamReceiveNestExcess::getNestId, reqVo.getNestId())
                                    .eq(SinoCamReceiveNestExcess::getStockListNo, reqVo.getPlateCode())
                                    .eq(SinoCamReceiveNestExcess::getExMaterielId, excessVo.getExcessCode())
                                    .list();
                            if (CollUtil.isEmpty(excessList)) {
                                SinoCamReceiveNestExcess excess = MkBeanUtils.copyProperties(excessVo, SinoCamReceiveNestExcess.class);
                                excess.setSinoCamId(scId);
                                excess.setReceiveNestId(scrnId);
                                excess.setNestId(reqVo.getNestId());
                                excess.setFactoryIdk("170");
                                excess.setStockListNo(excessVo.getPlateCode());
                                excess.setExMaterielId(excessVo.getExcessCode());
                                excess.setTexture(excessVo.getTexture());
                                excess.setNorm(excessVo.getThickness().toString());
                                excess.setWidth(excessVo.getWidth());
                                excess.setLength(excessVo.getLength());
                                excess.setWeight(excessVo.getWeight());
                                excess.setOutStock(0);
                                sinoCamReceiveNestExcessMapper.insert(excess);

                                log.info("余料:{}", JsonUtils.toJsonString(excess));
                            }
                        }

                        // 走刀
                        List<ReceiveNestMoveReqVo> moveList = reqVo.getMove();
                        List<SinoCamReceiveNestMove> moves = new ArrayList<>();
                        List<SinoCamReceiveNestMove> nm = sinoCamReceiveNestMoveMapper.lambdaQuery().eq(SinoCamReceiveNestMove::getNestId, reqVo.getNestId()).list();
                        if (CollUtil.isEmpty(nm)) {
                            if (CollUtil.isNotEmpty(moveList)) {
                                int totalTime = 0;
                                for (ReceiveNestMoveReqVo vo : moveList) {
                                    SinoCamReceiveNestMove move = MkBeanUtils.copyProperties(vo, SinoCamReceiveNestMove.class);
                                    move.setSinoCamId(scId);
                                    move.setReceiveNestId(scrnId);
                                    move.setNestId(reqVo.getNestId());
                                    move.setCutLength(vo.getCutLength());
                                    move.setFactoryIdk(vo.getFactoryCode());
                                    move.setMoveTime(vo.getMoveTime());
                                    move.setMoveType(vo.getMoveType());
                                    move.setHoleCount(vo.getHoleCount());
                                    move.setHoleTime(vo.getHoleTime());
                                    move.setTotalHoleTime(vo.getTotalHoleTime());
                                    move.setCutRate(vo.getCutRate());
                                    move.setTotalCutTime(vo.getTotalCutTime());
                                    totalTime = totalTime + vo.getTotalCutTime();
                                    moves.add(move);
                                }
                                for (SinoCamReceiveNestMove a : moves) {
                                    a.setTotalCutTime(totalTime);
                                }
                                sinoCamReceiveNestMoveMapper.insertBatchSomeColumn(moves);
                            } else {
                                SinoCamReceiveNestMove move1 = new SinoCamReceiveNestMove();
                                SinoCamReceiveNestMove move2 = new SinoCamReceiveNestMove();

                                move1.setSinoCamId(scId);
                                move1.setReceiveNestId(scrnId);
                                move1.setNestId(reqVo.getNestId());
                                move1.setCutLength(BigDecimal.valueOf(1));
                                move1.setFactoryIdk("170");
                                move1.setMoveTime(1);
                                move1.setMoveType(1);
                                move1.setHoleCount(1);
                                move1.setHoleTime(1);
                                move1.setTotalHoleTime(1);
                                move1.setCutRate(BigDecimal.valueOf(1));
                                move1.setTotalCutTime(1);
                                sinoCamReceiveNestMoveMapper.insert(move1);

                                move2.setSinoCamId(scId);
                                move2.setReceiveNestId(scrnId);
                                move2.setNestId(reqVo.getNestId());
                                move2.setCutLength(BigDecimal.valueOf(1));
                                move2.setFactoryIdk("170");
                                move2.setMoveTime(1);
                                move2.setMoveType(2);
                                move2.setHoleCount(1);
                                move2.setHoleTime(0);
                                move2.setTotalHoleTime(0);
                                move2.setCutRate(BigDecimal.valueOf(1));
                                move2.setTotalCutTime(1);
                                sinoCamReceiveNestMoveMapper.insert(move2);
                            }

                        }

                        List<Integer> planIdList = receiveParts.stream().map(e -> Integer.parseInt(e.getNestPlanId())).distinct().collect(Collectors.toList());
                        List<ApsWorkDetail> apsWorkDetails = apsWorkDetailMapper.selectBatchIds(planIdList);

                        // ---------- 推送到钢板信息表----
                        List<PlatePhase> platePhaseList = new ArrayList<>();
                        List<ApsWorkDetail> apsWorkDetailList = new ArrayList<>();
                        Map<String, PlatePhase> plateLlPhaseMap = new HashMap<>();
                        Plate mesPlate = new Plate();
                        List<ReceiveNestPartReqVo> nestParts = reqVo.getPart();
                        mesPlate.setMaterCode(reqVo.getPlateCode());// 钢板编号
                        mesPlate.setMaterName("钢板");// 钢板物料名称
                        mesPlate.setLength(reqVo.getLength());
                        mesPlate.setWidth(reqVo.getWidth());
                        mesPlate.setNorm(String.valueOf(reqVo.getThickness().setScale(0, RoundingMode.HALF_UP)));// 厚度
                        mesPlate.setTexture(reqVo.getTexture());
                        mesPlate.setStatus(1);
                        mesPlate.setHeatNumber(reqVo.getHeatId());

                        SinoCamReceiveNestExcess nestExcess = sinoCamReceiveNestExcessMapper.lambdaQuery().eq(SinoCamReceiveNestExcess::getStockListNo, reqVo.getPlateCode()).one();
                        BigDecimal weight = reqVo.getWeight();
                        if (nestExcess != null) {
                            weight = weight.subtract(nestExcess.getWeight());
                        }

                        mesPlate.setNestId(reqVo.getNestId());
                        mesPlate.setNestRate(reqVo.getRate());// 利用率
                        mesPlate.setNestDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER));// 套料日期
                        mesPlate.setNestingDrawing(mesPNG + reqVo.getPngUrl());// 套料图纸，PNG格式
                        mesPlate.setCutProcess(reqVo.getCuttingProgramUrl());// 切割程序下载地址
                        mesPlate.setWeight(reqVo.getWeight());
                        mesPlate.setNestWeight(weight.multiply(reqVo.getRate().divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP)));
                        mesPlate.setPickDateTime(plate.getPickDateTime());// 领料时间
                        mesPlate.setNestPlateId(plate.getId());
                        mesPlate.setNestLock(0);

                        PlatePhase llPhase = new PlatePhase();
                        llPhase.setPlateCode(plate.getStockListNo());
                        llPhase.setPhaseCode(WorkshopProp.LL_PHASE_CODE);
                        llPhase.setPhaseName(WorkshopProp.LL_PHASE_NAME);
                        llPhase.setGroupCode(WorkshopProp.LL_GROUP);
                        llPhase.setPhaseSeq(platePhaseList.size() + 1);
                        platePhaseList.add(llPhase);

                        ApsWorkDetail llApsWorkDetail = new ApsWorkDetail();
                        llApsWorkDetail.setMaterNo(plate.getStockListNo());
                        llApsWorkDetail.setMaterName("钢板");
                        llApsWorkDetail.setPhaseId(llPhase.getPhaseSeq());
                        llApsWorkDetail.setPhaseSeq(llPhase.getPhaseSeq());
                        llApsWorkDetail.setPhaseCode(WorkshopProp.LL_PHASE_CODE);
                        llApsWorkDetail.setPartCount(new BigDecimal(1));
                        llApsWorkDetail.setFinishCount(new BigDecimal(0));
                        llApsWorkDetail.setTotalCount(new BigDecimal(1));
                        llApsWorkDetail.setUniqueCode(plate.getStockListNo());
                        llApsWorkDetail.setStatus(2);
                        llApsWorkDetail.setPhaseName(WorkshopProp.LL_PHASE_NAME);
                        llApsWorkDetail.setPlanStartDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).minusHours(7));
                        llApsWorkDetail.setActualStartDateTime(LocalDateTime.now());
                        llApsWorkDetail.setPlanEndDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).minusHours(6));
                        llApsWorkDetail.setGroupCode(WorkshopProp.LL_GROUP);
                        llApsWorkDetail.setAppendFlag(2);
                        llApsWorkDetail.setType(1);
                        llApsWorkDetail.setTotalWorkTime(60 * 60);
                        llApsWorkDetail.setWorkTime(60 * 60);
                        if (CollUtil.isNotEmpty(apsWorkDetails)) {
                            llApsWorkDetail.setOrderId(apsWorkDetails.get(0).getOrderId());
                            llApsWorkDetail.setApsOrderId(apsWorkDetails.get(0).getApsOrderId());
                        }
                        apsWorkDetailList.add(llApsWorkDetail);

                        plateLlPhaseMap.put(plate.getStockListNo(), llPhase);

                        // 添加预处理工序
                        BigDecimal thickness = new BigDecimal(plate.getNorm());
                        if (thickness.compareTo(new BigDecimal(100)) < 0) { //钢板厚度小于100走预处理
                            PlatePhase phase = new PlatePhase();
                            phase.setPlateCode(plate.getStockListNo());
                            phase.setPhaseCode(WorkshopProp.YC_PHASE_CODE);
                            phase.setPhaseName("预处理");
                            phase.setGroupCode(WorkshopProp.YC_GROUP);
                            phase.setPhaseSeq(platePhaseList.size() + 1);
                            phase.setWorkTime(540);
                            platePhaseList.add(phase);

                            ApsWorkDetail ycApsWorkDetail = new ApsWorkDetail();
                            ycApsWorkDetail.setMaterNo(plate.getStockListNo());
                            ycApsWorkDetail.setMaterName("钢板");
                            ycApsWorkDetail.setPhaseId(phase.getPhaseSeq());
                            ycApsWorkDetail.setPhaseSeq(phase.getPhaseSeq());
                            ycApsWorkDetail.setPhaseCode(WorkshopProp.YC_PHASE_CODE);
                            ycApsWorkDetail.setPartCount(new BigDecimal(1));
                            ycApsWorkDetail.setFinishCount(new BigDecimal(0));
                            ycApsWorkDetail.setTotalCount(new BigDecimal(1));
                            ycApsWorkDetail.setUniqueCode(plate.getStockListNo());
                            ycApsWorkDetail.setStatus(2);
                            ycApsWorkDetail.setPhaseName("预处理");
                            ycApsWorkDetail.setPlanStartDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).minusHours(7));
                            ycApsWorkDetail.setPlanEndDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).minusHours(6));
                            ycApsWorkDetail.setGroupCode(WorkshopProp.YC_GROUP);
                            ycApsWorkDetail.setAppendFlag(2);
                            ycApsWorkDetail.setType(1);
                            ycApsWorkDetail.setTotalWorkTime(60 * 60);
                            ycApsWorkDetail.setWorkTime(60 * 60);
                            if (CollUtil.isNotEmpty(apsWorkDetails)) {
                                ycApsWorkDetail.setOrderId(apsWorkDetails.get(0).getOrderId());
                                ycApsWorkDetail.setApsOrderId(apsWorkDetails.get(0).getApsOrderId());
                            }
                            apsWorkDetailList.add(ycApsWorkDetail);
                        }

                        // 添加切割工序
                        PlatePhase splitPhase = new PlatePhase();
                        splitPhase.setPlateCode(plate.getStockListNo());
                        String phaseCode = hexagonNestOldUtils.getSplitCode(reqVo.getGroupCode(), reqVo.getNestId());
                        splitPhase.setPhaseCode(phaseCode);
                        splitPhase.setPhaseName(phaseCode.equals("JG") ? "激光切割" : "火焰切割");
                        splitPhase.setGroupCode(reqVo.getGroupCode());
                        splitPhase.setPhaseSeq(platePhaseList.size() + 1);
                        List<SinoCamReceiveNestMove> nestMoveList = sinoCamReceiveNestMoveMapper.lambdaQuery().eq(SinoCamReceiveNestMove::getNestId, reqVo.getNestId()).list();
                        if (CollUtil.isNotEmpty(nestMoveList)) {
                            splitPhase.setWorkTime(nestMoveList.get(0).getTotalCutTime());
                        } else {
                            splitPhase.setWorkTime(0);
                        }
                        platePhaseList.add(splitPhase);

                        ApsWorkDetail qgApsWorkDetail = new ApsWorkDetail();
                        qgApsWorkDetail.setMaterNo(plate.getStockListNo());
                        qgApsWorkDetail.setMaterName("钢板");
                        qgApsWorkDetail.setPhaseId(splitPhase.getPhaseSeq());
                        qgApsWorkDetail.setPhaseSeq(splitPhase.getPhaseSeq());
                        qgApsWorkDetail.setPhaseCode(phaseCode);
                        qgApsWorkDetail.setPartCount(new BigDecimal(1));
                        qgApsWorkDetail.setFinishCount(new BigDecimal(0));
                        qgApsWorkDetail.setTotalCount(new BigDecimal(1));
                        qgApsWorkDetail.setUniqueCode(plate.getStockListNo());
                        qgApsWorkDetail.setStatus(2);
                        qgApsWorkDetail.setPhaseName(phaseCode.equals("JG") ? "激光切割" : "火焰切割");
                        qgApsWorkDetail.setPlanStartDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER));
                        qgApsWorkDetail.setPlanEndDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).plusHours(2));
                        qgApsWorkDetail.setGroupCode(reqVo.getGroupCode());
                        qgApsWorkDetail.setAppendFlag(2);
                        qgApsWorkDetail.setType(1);
                        if (CollUtil.isNotEmpty(apsWorkDetails)) {
                            qgApsWorkDetail.setOrderId(apsWorkDetails.get(0).getOrderId());
                            qgApsWorkDetail.setApsOrderId(apsWorkDetails.get(0).getApsOrderId());
                        }
                        qgApsWorkDetail.setTotalWorkTime(2 * 60 * 60);
                        qgApsWorkDetail.setWorkTime(2 * 60 * 60);
                        apsWorkDetailList.add(qgApsWorkDetail);

                        // 添加分捡工序
                        Map<String, String> fjGroup = new HashMap<>();
                        fjGroup.put("1-1_HYQG_00", "1-1_RGFJ_00");
                        fjGroup.put("1-2_JGQG_00", "1-2_ZDFJ_00");
                        fjGroup.put("1-3_JGQG_00", "1-3_ZDFJ_00");

                        PlatePhase fjPhase = new PlatePhase();
                        fjPhase.setPlateCode(plate.getStockListNo());
                        fjPhase.setPhaseCode(WorkshopProp.FJ_PHASE_CODE);
                        fjPhase.setPhaseName("分捡");
                        fjPhase.setGroupCode(fjGroup.get(reqVo.getGroupCode()));
                        fjPhase.setPhaseSeq(platePhaseList.size() + 1);
                        platePhaseList.add(fjPhase);

                        ApsWorkDetail fjApsWorkDetail = new ApsWorkDetail();
                        fjApsWorkDetail.setMaterNo(plate.getStockListNo());
                        fjApsWorkDetail.setMaterName("钢板");
                        fjApsWorkDetail.setPhaseId(fjPhase.getPhaseSeq());
                        fjApsWorkDetail.setPhaseSeq(fjPhase.getPhaseSeq());
                        fjApsWorkDetail.setPhaseCode(WorkshopProp.FJ_PHASE_CODE);
                        fjApsWorkDetail.setPartCount(new BigDecimal(1));
                        fjApsWorkDetail.setFinishCount(new BigDecimal(0));
                        fjApsWorkDetail.setTotalCount(new BigDecimal(1));
                        fjApsWorkDetail.setUniqueCode(plate.getStockListNo());
                        fjApsWorkDetail.setStatus(2);
                        fjApsWorkDetail.setPhaseName("分捡");
                        fjApsWorkDetail.setPlanStartDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).plusHours(2));
                        fjApsWorkDetail.setPlanEndDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).plusHours(5));
                        fjApsWorkDetail.setGroupCode(fjGroup.get(reqVo.getGroupCode()));
                        fjApsWorkDetail.setAppendFlag(2);
                        fjApsWorkDetail.setType(1);

                        fjApsWorkDetail.setTotalWorkTime(3 * 60 * 60);
                        fjApsWorkDetail.setWorkTime(3 * 60 * 60);
                        if (CollUtil.isNotEmpty(apsWorkDetails)) {
                            fjApsWorkDetail.setOrderId(apsWorkDetails.get(0).getOrderId());
                            fjApsWorkDetail.setApsOrderId(apsWorkDetails.get(0).getApsOrderId());
                        }
                        apsWorkDetailList.add(fjApsWorkDetail);

                        mesPlate.setWorkChain(platePhaseList.stream().map(PlatePhase::getPhaseCode).collect(Collectors.joining("-")));

                        plateMapper.insert(mesPlate);

                        Plate plateId = plateMapper.lambdaQuery().eq(Plate::getMaterCode, mesPlate.getMaterCode()).one();
                        for (PlatePhase platePhase : platePhaseList) {
                            platePhase.setPlateId(plateId.getId());
                        }
                        platePhaseMapper.insertBatch(platePhaseList);

                        apsWorkDetailMapper.insertBatchSomeColumn(apsWorkDetailList);

                        WmsPlatePick pick = new WmsPlatePick();

                        pick.setPlateState(1);
                        pick.setNextWorkPlace(reqVo.getGroupCode());
                        pick.setNestPlateId(plate.getId());
                        pick.setAmount(1);// 数量
                        pick.setLength(plate.getLength());
                        pick.setWidth(plate.getWidth());
                        pick.setFastFlag(0);
                        pick.setReceiveDate(LocalDateTime.now());
                        pick.setPlannedStartTime(plate.getPickDateTime());// 领料时间
                        pick.setType(1);
                        pick.setMaterialCode(plate.getStockListNo());// 厚度
                        pick.setPlateMaterial(plate.getTexture());
                        pick.setPlateThick(plate.getNorm());// 厚度
                        pick.setMaterialId(plate.getStockListNo());// 钢板编号（钢板物料号/材料编号？）
                        pick.setPlateUsage(plate.getRate());// 利用率
                        pick.setNesting(mesPNG + reqVo.getPngUrl());// 套料图号
                        pick.setMaterName(plate.getMaterielName());// 钢板物料名称

                        pick.setPickingListNo(null);
                        pick.setPlanDate(null);
                        pick.setPackageSn(null);
                        pick.setWantDeliverDate(null);
                        pick.setStoragePlace(plate.getPositionCode());
                        pick.setSeq(plate.getSequence());
                        pick.setPickListItem(null);
                        pick.setPlateWeight(mesPlate.getWeight());// 钢板重量
                        pick.setCloutWeight(null);
                        pick.setOutTime(null);
                        pick.setPlateNote(null);
                        pick.setPlateId(mesPlate.getId());// 钢板ID
                        pick.setPlannedStartTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER));// 需求日期
                        pick.setNestId(reqVo.getNestId());
                        pick.setPickDateTime(null);
                        pick.setPickId(null);
                        wmsPlatePickMapper.insert(pick);
                    }
                    nestCheck.setCheckState(1);
                }
            } catch (Exception e) {
                nestCheck.setCheckState(2);
            }
            sinoCamReceiveNestCheckMapper.updateById(nestCheck);
        }

    }

    public void checkPlateNestInfo() {
        List<ApsWorkDetail> plateDetailList = apsWorkDetailMapper.lambdaQuery()
                .in(ApsWorkDetail::getPhaseCode, "JG", "HG")
                .ne(ApsWorkDetail::getStatus, 4)
                .eq(ApsWorkDetail::getType, 1)
                .list();
        if (CollUtil.isEmpty(plateDetailList)) {
            return;
        }
        for (ApsWorkDetail p : plateDetailList) {
            ReceiveNestPlateReqVo vo = apsMesFeign.checkNestPlate(p.getMaterNo());
            if (ObjectUtils.isEmpty(vo)) {
                sinoCamService.clearNestResultInfoPlate(p.getMaterNo());

                List<WorkRecord> plateRecord = workRecordMapper.lambdaQuery().eq(WorkRecord::getPalletNumber, p.getMaterNo()).eq(WorkRecord::getType, 1).list();
                for (WorkRecord r : plateRecord) {
                    workRecordMapper.deleteWithId(r.getId());
                }

                // 清除钢板在制品
                partMapper.deletePlate(p.getMaterNo());

                LogNestExce logNestExce = new LogNestExce();
                logNestExce.setAppId("MES套料");
                logNestExce.setPlateCode(p.getMaterNo());
                logNestExce.setConstructNo(p.getMaterNo());
                logNestExce.setNestId(p.getMaterNo());
                logNestExce.setPartId(p.getMaterNo());
                logNestExce.setQuantity(1);
                logNestExce.setNote("钢板套料结果删除。");
                logNestExce.setInfoState(0);
                logNestExceMapper.insert(logNestExce);
            }
        }
    }

}
